package com.zjc.tcploadbalance.controller;

import com.zjc.tcploadbalance.RegisterClient;
import com.zjc.tcploadbalance.config.InstanceConfig;
import com.zjc.tcploadbalance.model.InstanceModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class LoadBalanceController {

    @Autowired
    RegisterClient registerClient;

    @Autowired
    private InstanceConfig instanceConfig;

    @GetMapping("v1/tcpLoadBalance/leastLoad.instance")
    public String getOptimalInstance() {
        List<InstanceModel> instanceModels = registerClient.getInstanceModels();
        if (instanceModels.size() > 0) {
            return leastLoadInstance(instanceModels);
        } else {
            return instanceConfig.getInstanceId();
        }
    }


    private String leastLoadInstance(List<InstanceModel> instanceModels) {

        String instanceId = instanceModels.get(0).getInstanceId();
        Long load = instanceModels.get(0).getLoadCount();
        int index = 0;
        if (instanceModels.size() > 1) {
            for (int i = 1; i < instanceModels.size(); i++) {
                if (instanceModels.get(i).getLoadCount() < load) {
                    load = instanceModels.get(i).getLoadCount();
                    index = i;
                    instanceId = instanceModels.get(i).getInstanceId();
                }
            }
        }
        instanceModels.get(index).setLoadCount(load + 1);
        return instanceId;
    }
}
